from selenium import webdriver
import time
import ddddocr
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

ocr = ddddocr.DdddOcr()

options = webdriver.ChromeOptions()
options.add_experimental_option('excludeSwitches', ['enable-automation'])
options.add_argument("--disable-blink-features=AutomationControlled")
driver = webdriver.Chrome(options=options)
driver.maximize_window()

driver.get("http://hngcjs.hnjs.henan.gov.cn/creit/creitListView")
time.sleep(5)

i = 1
while i < 1055:
    iframe_exists = False

    try:
        # 尝试查找验证码iframe，超时时间设为2秒快速判断
        iframe = WebDriverWait(driver, 2).until(
            EC.presence_of_element_located((By.XPATH, "//iframe[contains(@id, 'layui-layer-iframe')]"))
        )
        iframe_exists = True
        print("检测到验证码iframe")
        if iframe_exists:
            if i != 1:
                i -= 1
            # 转到验证码界面
            driver.switch_to.frame(driver.find_element("xpath", "//iframe[@id='layui-layer-iframe100001']"))
            for n in range(1, 21):
                time.sleep(3)
                driver.find_element("xpath", "//img[@class='imgcode']").screenshot(f"验证码{n}.png")
                image = open(f"验证码{n}.png", "rb").read()
                result = ocr.classification(image)
                print(f"验证码:{result}")
                driver.find_element("xpath", "//input[@id='yanzhengma']").send_keys(result)
                time.sleep(1)
                driver.find_element("xpath", "//button[@class='btn btn-primary']").click()
                time.sleep(3)
                if "验证码错误" in driver.page_source:
                    print(f"验证码错误")
                    print(f"开始重试第{n}次")
                    continue
                break
    except:
        print("未检测到验证码iframe")
    # 转到主界面
    driver.switch_to.default_content()
    time.sleep(3)
    data_list = driver.find_elements("xpath", "//tbody/tr")
    for data in data_list:
        company = data.find_element("xpath", "./td[2]").text
        believe = data.find_element("xpath", "./td[3]").text
        department = data.find_element("xpath", "./td[4]").text
        date = data.find_element("xpath", "./td[7]").text
        print(f"{i}, {company}, {believe}, {department}, {date}")
    # 模拟滑动动作
    driver.execute_script("window.scrollTo(0, document.body.scrollHeight)")
    time.sleep(1)

    # 模拟人点击翻页
    i += 1
    input_element = driver.find_element("xpath", "//input[@type='number' and contains(@class, 'form-control')]")
    # 用 JavaScript 修改 value
    driver.execute_script("arguments[0].value = arguments[1];", input_element, i)  # 改成 5
    driver.find_element("xpath", "//span[@class='input-group-btn']/button[@class='btn btn-default']").click()
    time.sleep(3)
